import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
plt.rc("figure", figsize=(12,9))
from scipy import stats
d = 10
etats = np.arange(d)
probas = np.random.rand(d)
loi = stats.rv_discrete(values=(etats, probas/np.sum(probas)))
loi.rvs(size=(20))
x = np.linspace(0, d, 50)
y = loi.cdf(x)
plt.plot(x, y, lw=2)
print("moyenne : ", loi.mean())
print("variance : ", loi.var())
print("médiane : ", loi.median())
print("moment d'ordre 3 : ", loi.moment(3))
X, Y = np.random.rand(2, 20000)
x, y = np.cumsum(2*X-1), np.cumsum(2*Y-1)
plt.scatter(x, y, c=range(len(x)), marker=".")
plt.gca().set_aspect("equal")
def stoch(d):
P = np.random.rand(d, d)
s = np.reshape(np.sum(P, axis=1), newshape=(d, 1))
return P/s
stoch(5)
Q = np.cumsum(P, axis=1)
Q
def mc(i0, n, P):
"""
i0 : état de départ
n : longeur de simulation
P : matrice de transition
"""
Q = np.cumsum(P, axis=1)
def saut(i, t):
return np.sum((Q[i,:] < t))
etats = i0*np.ones(shape=(n), dtype=int)
variable = np.random.rand(n-1)
for k in range(n-1):
etats[k+1] = saut(etats[k], variable[k])
return etats
def aff(nbs, etatmax=15):
P = stoch(etatmax)
depart = np.random.randint(0, etatmax)
wd = 0.8/len(nbs)
for i, nb in enumerate(nbs):
val, freq = np.unique(mc(depart, nb, P), return_counts=True)
plt.bar(val + i*wd, freq/nb, width=wd, label="{}".format(nb))
plt.legend(loc="best")
%%time
aff([10_000, 50_000, 100_000])
%%time
aff([10_000, 50_000, 100_000, 200_000])